package com.handu.luna.boss.controller;

import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.List;

import javax.validation.Valid;

import com.handu.luna.core.domain.promotion.CreditPromotionGoods;
import com.handu.luna.core.domain.promotion.Promotion;
import com.handu.luna.core.domain.search.CreditPromotionSearch;
import net.sf.json.JSONObject;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.handu.luna.core.domain.promotion.CreditPromotion;


@Controller
@RequestMapping("/promotion/credit/*")
public class CreditPromotionController extends BaseController{

    @RequestMapping(value = "list",method = RequestMethod.GET)
    public BossModel list(String viewState,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE,sort = "id",direction = Sort.Direction.DESC) Pageable pageable) throws UnsupportedEncodingException {

        CreditPromotionSearch creditPromotionSearch;
        BossModel bossModel = createModel("promotion/credit/list");
		if(viewState != null && !viewState.trim().equals("")){
			creditPromotionSearch = (CreditPromotionSearch) JSONObject.toBean(JSONObject.fromObject(new String(Base64.getDecoder().decode(viewState), "UTF-8")), CreditPromotionSearch.class);
		}else{
			creditPromotionSearch = new CreditPromotionSearch();
            viewState = "";
		}
        return bossModel.add("creditPromotionPage",context.getCreditPromotionRepository().findAll(CreditPromotion.selectCondition(creditPromotionSearch),pageable))
                .add("creditPromotionSearch",creditPromotionSearch)
                .add("statusValues", Promotion.PromotionStatus.values())
                .add("viewState", viewState);
	}

    @RequestMapping(value = "list",method = RequestMethod.POST)
    public BossModel list(CreditPromotionSearch creditPromotionSearch,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE,sort = "id",direction = Sort.Direction.DESC) Pageable pageable) throws UnsupportedEncodingException {
        BossModel bossModel = createModel();
        return bossModel.add("creditPromotionPage",context.getCreditPromotionRepository().findAll(CreditPromotion.selectCondition(creditPromotionSearch),pageable))
                .add("creditPromotionSearch",creditPromotionSearch)
                .add("statusValues", Promotion.PromotionStatus.values())
                .add("viewState",Base64.getUrlEncoder().encodeToString(JSONObject.fromObject(creditPromotionSearch).toString().getBytes("UTF-8")));
	}

	/*@RequestMapping(value="list")
	public BossModel list(@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE) Pageable pageable){
		return this.createModel("promotion/credit/list")
                .add("creditPromotionList", context.getCreditPromotionRepository().findAll(pageable));
	}*/
	
	@RequestMapping(value="edit/{id}")
	public BossModel edit(@PathVariable long id){
		return createModel("promotion/credit/info")
                .add("userRanks", context.getUserRankRepository().findAllNotSpecial())
                .add("creditPromotion", context.getCreditPromotionRepository().findOne(id))
                .add("creditTypeValues", CreditPromotion.CreditType.values())
                .add("creditCategoryValues", CreditPromotion.CreditCategory.values());
	}
	
	@RequestMapping(value="save",method = RequestMethod.POST)
	public BossModel save(@Valid @ModelAttribute("creditPromotion") final CreditPromotion creditPromotion, final BindingResult bindingResult, final ModelMap model, RedirectAttributes redirectAttributes){
		if(creditPromotion.getStartTime() == null) {
			bindingResult.rejectValue("startTime", "misFormat", "请输入开始日期");
		}
		if(creditPromotion.getEndTime() == null) {
			bindingResult.rejectValue("endTime", "misFormat", "请输入结束日期");
		}
		if(creditPromotion.getStartTime() != null && creditPromotion.getEndTime() != null) {
			if(creditPromotion.getStartTime().compareTo(creditPromotion.getEndTime()) != -1) {
				bindingResult.rejectValue("startTime", "misFormat", "开始时间必须小于结束时间");
			}
		}
//		if(creditPromotion.getCreditName().trim().equals("")){
//			bindingResult.rejectValue("creditName", "", "请输入名称");
//		}
		
		if (bindingResult.hasErrors()) {
			return createModel("promotion/credit/info")
                    .add("userRanks", context.getUserRankRepository().findAllNotSpecial())
                    .add("creditTypeValues", CreditPromotion.CreditType.values())
                    .add("creditCategoryValues", CreditPromotion.CreditCategory.values());
		}
        String message ;
        if(creditPromotion.isNew()) {
            context.getCreditPromotionRepository().save(creditPromotion);
            message = "添加\t" + creditPromotion.getCreditName() + "\t成功";
        }else {
            creditPromotion.update();
            message = "修改\t" + creditPromotion.getCreditName() + "\t成功";
        }


		redirectAttributes.addFlashAttribute("message", message);
		return createModel("redirect:list");
	}
	
	@RequestMapping(value="add")
	public BossModel add(){

        CreditPromotion creditPromotion = new CreditPromotion();
        creditPromotion.setCreditType(CreditPromotion.CreditType.CREDIT);
		return createModel("promotion/credit/info")
                .add("userRanks", context.getUserRankRepository().findAllNotSpecial())
                .add("creditTypeValues", CreditPromotion.CreditType.values())
                .add("creditCategoryValues", CreditPromotion.CreditCategory.values())
                .add("creditPromotion", creditPromotion);
    }

    @RequestMapping(value="delete",method= RequestMethod.POST)
	public BossModel delete(long id,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE,sort = "id",direction = Sort.Direction.DESC) Pageable pageable,String viewState){

		//context.getCreditPromotionRepository().findOne(id);
        if(viewState == null || viewState.trim().equals("")){
            viewState = "";
        }

        List<CreditPromotionGoods> creditPromotionGoodsList = context.getCreditPromotionGoodsRepository().findByCreditPromotionId(id);
        for(CreditPromotionGoods creditPromotionGoods : creditPromotionGoodsList) {
            context.getCreditPromotionGoodsRepository().delete(creditPromotionGoods);
        }
		context.getCreditPromotionRepository().delete(id);
		return createModel("promotion/credit/creditPromotion_table")
                .add("creditPromotionPage", context.getCreditPromotionRepository().findAll(pageable))
                .add("viewState",viewState);
	}
}
